﻿using System;

namespace ZR.Infrastructure.Resolver;

public static class AntPathMatcher
{
    public static bool Match(string pattern, string value)
    {
        if (pattern == null || value == null)
            return false;

        if (pattern == "**")
            return true;

        var patternSegments = pattern.Split('/');
        var valueSegments = value.Split('/');

        int patternIndex = 0;
        int valueIndex = 0;
        int patternWildcardIndex = -1;
        int valueWildcardIndex = -1;

        while (valueIndex < valueSegments.Length)
        {
            if (patternIndex < patternSegments.Length && IsMatch(patternSegments[patternIndex], valueSegments[valueIndex]))
            {
                patternIndex++;
                valueIndex++;
            }
            else if (patternWildcardIndex != -1)
            {
                patternIndex = patternWildcardIndex + 1;
                valueIndex = ++valueWildcardIndex;
            }
            else
            {
                return false;
            }
        }

        while (patternIndex < patternSegments.Length && patternSegments[patternIndex] == "**")
        {
            patternIndex++;
        }

        return patternIndex >= patternSegments.Length && valueIndex >= valueSegments.Length;
    }

    private static bool IsMatch(string patternSegment, string valueSegment)
    {
        if (patternSegment == "*")
            return true;

        if (patternSegment.StartsWith("{") && patternSegment.EndsWith("}"))
            return true; // 支持占位符的匹配逻辑

        return string.Equals(patternSegment, valueSegment, StringComparison.OrdinalIgnoreCase);
    }
}